﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Exchange.WebServices.Data;
using System.Net;

namespace TesteOutlook
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create ExchangeService object
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
            //Assign the URL. It is recommended to use AutoDiscoverUrl but we didn’t have it configured
            service.Url = new Uri("https://sjcsrvvmmail01.gsw.com.br/EWS/Exchange.asmx");

            //Set service credentials. In this case a user account who has permissions to user mailboxes.
            string domain = "GSW";
            string credUser = "francir";
            string credPwd = "fran$07";
            
            service.Credentials = new NetworkCredential(credUser, credPwd, domain);

            //Set the user who is logged in and whose mailbox needs to be checked for unread emails.
            //string impUser = "francir@gsw.com.br";
            //service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, impUser);

            //Bind the Inbox folder to the service object
            Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);

            //The search filter to get unread email
            SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            ItemView view = new ItemView(20);
            
            //Fire the query for the unread items
            FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);

            //Loop through the items and do whatever is required.

            foreach (EmailMessage item in findResults)
            {
                Console.WriteLine("Data: " + item.DateTimeReceived.ToString());
                Console.WriteLine(item.Subject);
                Console.WriteLine("");

                if (item.HasAttachments)
                {
                    item.Load();
                    if (item.Attachments[0] is FileAttachment)
                    {
                        FileAttachment fileAttachment = item.Attachments[0] as FileAttachment;
                        fileAttachment.Load("C:\\temp\\" + fileAttachment.Name);
                    }
                }

                item.IsRead = true;
                item.Update(ConflictResolutionMode.AlwaysOverwrite);
            }
            

            Console.ReadKey();
        }
    }
}
